import { reactive, watch, computed } from '@vue/composition-api'
import router from '@/router/index'

const stepRouter = {
  order: [
    '/customer/report/order/index',
    '/customer/report/order/goods',
    '/customer/report/order/confirm',
  ],
  biding: [
    '/customer/report/biding/index',
    '/customer/report/biding/goods',
    '/customer/report/biding/confirm',
  ],
}

const saveCache = (type, data) => {
  localStorage.setItem(`report-${type}`, JSON.stringify({ data: data }))
}

const getCache = (type, defaultValue = null) => {
  try {
    return JSON.parse(localStorage.getItem(`report-${type}`)).data
  } catch (error) {
    return defaultValue
  }
}

const reportState = reactive({
  type: getCache('type', 'order'), // order | biding
  step: getCache('step', 0),
  form: getCache('form', {}),
  currentStepData: computed(() => stepRouter[reportState.type]),
  isLastStep: computed(() => reportState.currentStepData.length === reportState.step),
})

const reportReset = () => {
  reportState.type = 'order'
  reportState.step = 0
  reportState.form = {}
  console.log('reportReset', reportState.step)
}

// eslint-disable-next-line no-return-assign
const onSetType = type => reportState.type = type
const onStepNext = async () => {
  const is = await currentValidateForm()
  if (is) {
    reportState.step++
    gotoReport()
  }
}
const onStepPrev = async () => {
  if (reportState.step > 0) {
    reportState.step--
    if (reportState.step === 0) {
      reportReset()
    }
    gotoReport()
  }
}

let currentValidateForm = () => {
  return true
}

const gotoReport = (replace = true) => {
  const { step } = reportState
  console.log('step', step)
  let url = '/customer/report/index'
  if (step > 0) {
    url = stepRouter[reportState.type][step - 1]
  }
  if (url !== router.app.$route.path) { router[replace ? 'replace' : 'push'](url) }
}

// watch 要保存的data
watch(
  [() => reportState.type, () => reportState.step, () => reportState.form],
  () => {
    saveCache('type', reportState.type)
    saveCache('step', reportState.step)
    saveCache('form', reportState.form)
  },
  { deep: true },
)

export function useReport (_validateForm = () => true) {
  // const vm = getCurrentInstance()

  currentValidateForm = _validateForm

  // watch(
  //   () => reportState.step,
  //   step => {
  //     let url = '/customer/report'
  //     if (step > 0) {
  //       url = stepRouter[reportState.type][step - 1]
  //     }
  //     if (vm.$route.path.indexOf('/customer/report') === 0 && vm.$route.path !== url) {
  //       vm.$router.replace(url)
  //     }
  //   },
  //   { immediate: true },
  // )
  return {
    reportState,
    onSetType,
    onStepNext,
    onStepPrev,
    reportReset,
    gotoReport,
  }
}
